import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

function save(listData) {
  window.localStorage.setItem('listData', JSON.stringify(listData))
}

export default new Vuex.Store({
  state: {
    taskName: '',
    list: [],
    idIndex: null,
    activeListName: 'all'
  },
  mutations: {
    // 初始化数据
    initList(state, listData) {
      state.list = listData
    },
    // 双向数据绑定
    setNewTaskName(state, newTaskName) {
      state.taskName = newTaskName
    },
    // 添加事项
    addTask(state) {
      const obj = {
        id: Math.max(...state.list.map(v => v.id)) + 1,
        info: state.taskName,
        done: false
      }
      state.list.unshift(obj)
      save(state.list)
    },
    // 删除事项
    delTask(state, id) {
      state.list = state.list.filter(v => v.id !== id)
      save(state.list)
    },
    // 改变事项状态
    changeStatus(state, obj) {
      const task = state.list.find(v => v.id === obj.id)
      task.done = obj.done
      save(state.list)
    },
    // 删除全部
    clear(state) {
      state.list = state.list.filter(v => v.done === false)
      save(state.list)
    },
    // list切换
    changeList(state, activeListName) {
      state.activeListName = activeListName
    }
  },
  actions: {},
  getters: {
    doneLength(state) {
      return state.list.filter(v => !v.done).length
    },
    activeList(state) {
      if (state.activeListName === 'all') {
        return state.list
      }
      if (state.activeListName === 'undone') {
        return state.list.filter(v => v.done === false)
      }
      if (state.activeListName === 'done') {
        return state.list.filter(v => v.done === true)
      }
    }
  },
  modules: {}
})
